package com.kaigejava.ack;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;

/**
 * Created by kaigejava on 2019/7/21.
 */
public class MyConsumer extends DefaultConsumer {
    private Channel channel;
    public MyConsumer(Channel channel) {
        super(channel);
        this.channel = channel;
    }

    /**
     *
     * @param consumerTag       消费标签
     * @param envelope          envelope对象。里面有很多关键西悉尼
     * @param properties
     * @param body
     * @throws IOException
     */
    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        System.err.println("-----------consume message----------");
        System.err.println("body: " + new String(body));
        super.handleDelivery(consumerTag, envelope, properties, body);
        //获取num进行处理
        Integer num =(Integer)properties.getHeaders().get("num");

        try {
            System.out.println("当前消费的num是:{}"+num);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(num == 0){
            /**
             * 参数：
             *  long deliveryTag：消息标签
             *  boolean multiple：是否批量
             *  boolean requeue：是否重回队列
             *  如果设置成true,那么失败的消息会重新放到消息的最后
             */
            channel.basicNack(envelope.getDeliveryTag(),false,true);
        }else{
            //手动ack
            channel.basicAck(envelope.getDeliveryTag(),false);
        }
    }
}
